<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-title">Keep登录</div>
      <el-form :model="form" :rules="smsRules" ref="smsFormRef" @keyup.enter="onSmsSubmit">
        <el-form-item prop="phone">
          <el-input v-model="form.phone" placeholder="手机号" maxlength="11">
            <template #prefix><el-icon><Cellphone /></el-icon></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="smsCode">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input v-model="form.smsCode" placeholder="验证码" maxlength="6">
                <template #prefix><el-icon><Message /></el-icon></template>
              </el-input>
            </el-col>
            <el-col :span="8">
              <el-button :disabled="smsCountdown>0" @click="sendSmsCode" block>
                {{ smsCountdown>0 ? `${smsCountdown}s后重发` : '发送验证码' }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="onSmsSubmit" :loading="loading" round block>登录</el-button>
        </el-form-item>
      </el-form>
      <div class="divider" style="margin: 24px 0 12px 0; text-align: center; color: #bbb; font-size: 14px;">或</div>
      <el-button class="dingtalk-btn" @click="handleDingtalkLogin" round block>
        <span class="dingtalk-logo-bg">
          <img src="/dingtalk.png" class="dingtalk-logo" alt="钉钉" />
        </span>
      </el-button>
      <el-button class="guest-btn" @click="handleGuestLogin" round block style="margin-top: 16px; background: #e0e7ef; color: #333;">
        游客登录
      </el-button>
      <el-dialog v-model="captchaDialogVisible" title="请输入图片验证码" width="360px" :close-on-click-modal="false">
        <div style="text-align:center;">
          <img :src="'data:image/png;base64,' + captchaImg" @click="refreshCaptcha" style="cursor:pointer; width: 160px; height: 60px; display: block; margin: 0 auto;" />
          <div style="margin-top:12px;">
            <el-input v-model="captchaCode" placeholder="请输入图片验证码" maxlength="4" style="width: 200px; font-size: 20px;" size="large" />
          </div>
        </div>
        <template #footer>
          <el-button @click="captchaDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onCaptchaConfirm" :loading="captchaLoading">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Cellphone, Message } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()

// 验证码登录相关变量和方法
const loading = ref(false)
const smsCountdown = ref(0)
let smsTimer = null

const form = reactive({
  phone: '',
  smsCode: ''
})

const smsRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码为4位数字', trigger: 'blur' }
  ]
}
const smsFormRef = ref()

const onSmsSubmit = async () => {
  await smsFormRef.value.validate(async (valid) => {
    if (!valid) return
    loading.value = true
    try {
      const res = await request.post('http://127.0.0.1:8000/login/sms_login/', {
        phone: form.phone,
        sms_code: form.smsCode
      })
      if (res.token && res.userid) {
        ElMessage.success('登录成功')
        // 保存 token、userid 等
        localStorage.setItem('token', res.token.replace(/^Bearer\s+/i, ''))
        localStorage.setItem('userid', res.userid)
        router.push('/home')
      } else {
        ElMessage.error(res.msg || '登录失败')
      }
    } catch (e) {
      ElMessage.error(e?.response?.data?.error || '登录失败')
    } finally {
      loading.value = false
    }
  })
}

// 发送短信验证码相关
const captchaDialogVisible = ref(false)
const captchaImg = ref('')
const captchaKey = ref('')
const captchaCode = ref('')
const captchaLoading = ref(false)

const getCaptcha = async () => {
  try {
    const res = await request.get('http://127.0.0.1:8000/login/captcha/')
    if (res && res.captcha_img && res.captcha_key) {
      captchaImg.value = res.captcha_img
      captchaKey.value = res.captcha_key
      captchaCode.value = ''
    } else {
      captchaImg.value = ''
      captchaKey.value = ''
      ElMessage.error('获取验证码失败')
    }
  } catch (e) {
    captchaImg.value = ''
    captchaKey.value = ''
    ElMessage.error('获取验证码失败')
  }
}
const refreshCaptcha = () => getCaptcha()

const sendSmsCode = async () => {
  if (!/^1[3-9]\d{9}$/.test(form.phone)) {
    ElMessage.warning('请先输入正确的手机号')
    return
  }
  await getCaptcha()
  captchaDialogVisible.value = true
}

const onCaptchaConfirm = async () => {
  if (!captchaCode.value) {
    ElMessage.warning('请输入图片验证码')
    return
  }
  captchaLoading.value = true
  try {
    const res = await request.post('http://127.0.0.1:8000/login/send_sms/', {
      phone: form.phone,
      captcha_key: captchaKey.value,
      captcha_code: captchaCode.value
    })
    ElMessage.success('验证码已发送')
    captchaDialogVisible.value = false
    // 启动倒计时
    smsCountdown.value = 60
    smsTimer = setInterval(() => {
      smsCountdown.value--
      if (smsCountdown.value <= 0) {
        clearInterval(smsTimer)
        smsTimer = null
      }
    }, 1000)
  } catch (e) {
    ElMessage.error(e?.response?.data?.error || '发送失败')
    await getCaptcha()
  } finally {
    captchaLoading.value = false
  }
}

// 钉钉扫码登录
const handleDingtalkLogin = async () => {
  try {
    const response = await request.get('http://127.0.0.1:8000/login/dingtalk_auth_url/')
    if (response.code === 200 && response.url) {
      // 跳转前先清空旧头像
      localStorage.removeItem('avatar')
      window.location.href = response.url
    } else {
      ElMessage.error('获取钉钉登录URL失败')
    }
  } catch (e) {
    ElMessage.error('获取钉钉登录URL失败')
  }
}

// 钉钉回调后，获取并保存头像
async function fetchDingtalkAvatar(userid) {
  try {
    const res = await request.get('http://127.0.0.1:8000/login/get_thirdparty_avatar_by_userid/', {
      params: { userid }
    })
    if (res.avatar_url) {
      localStorage.setItem('avatar', res.avatar_url)
      // 如果有 userStore，更新 userStore.avatar
      if (typeof useUserStore === 'function') {
        const userStore = useUserStore()
        userStore.avatar = res.avatar_url
      }
    }
  } catch (e) {
    // 可以根据需要提示错误
  }
}

// 游客登录
const handleGuestLogin = () => {
  localStorage.setItem('token', 'guest-token')
  localStorage.setItem('userid', 'guest')
  ElMessage.success('以游客身份登录')
  router.push('/home')
}

// 处理第三方登录回调，保存token和userid
onMounted(() => {
  const token = route.query.token
  const userid = route.query.userid
  if (token) {
    localStorage.setItem('token', token.replace(/^Bearer\s+/i, ''))
  }
  if (userid) {
    localStorage.setItem('userid', userid)
  }
  // 只要有token和userid，强制跳转到/home，并清除URL参数
  if (token && userid) {
    router.replace({ path: '/home' })
  }
})

</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  background: linear-gradient(135deg, #e0e7ef 0%, #f8fafc 100%);
}
.login-box {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 6px 32px 0 rgba(44,62,80,0.10);
  padding: 56px 48px 40px 48px;
  width: 420px;
  max-width: 98vw;
  min-height: 340px;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 7vh;
}
.login-title {
  font-size: 2.3rem;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 38px;
  letter-spacing: 2px;
}
.login-btn {
  width: 100%;
  font-size: 1.2rem;
  height: 50px;
}
.el-input {
  font-size: 1.1rem;
  height: 44px;
}
.divider {
  width: 100%;
  height: 1px;
  background-color: #bbb;
  margin: 24px 0 12px 0;
}
.dingtalk-btn {
  background: transparent;
  box-shadow: none;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 8px;
  height: 64px;
  min-width: 64px;
  padding: 0;
  border-radius: 50%;
  transition: box-shadow 0.2s;
}
.dingtalk-logo-bg {
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 2px 12px 0 rgba(44,62,80,0.10);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  transition: box-shadow 0.2s, transform 0.2s;
}
.dingtalk-btn:hover .dingtalk-logo-bg {
  box-shadow: 0 4px 20px 0 rgba(0,132,255,0.18);
  transform: scale(1.08);
}
.dingtalk-logo {
  width: 44px;
  height: 44px;
  display: block;
  border-radius: 12px;
}
@media (max-width: 480px) {
  .login-box {
    padding: 32px 4vw 24px 4vw;
    width: 98vw;
    min-height: unset;
  }
  .login-title {
    font-size: 1.3rem;
  }
}
</style>
